import React, { useState } from 'react';
import styles from './index.less';
import { Modal, Table, Tooltip } from 'antd';
import { connect } from 'umi';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { programOverviewModal, question } from '@/assets';
import { conflict } from '@/assets/rollingBatch';
import { fetchUnitSubmitInfos } from '@/pages/Tianji/RollingBatch/services';

import messageConstant from '../../constant/message';
import { TRADE_STRATEGY, LOCKED_TYPE } from '../../constant/enums';

const { Column } = Table;

function ProgramOverviewModal({ currentSequenceId, menuCode }, ref) {
  React.useImperativeHandle(ref, () => ({ initHandle }));

  const [showModal, setShowModal] = useState(false),
    [columnData, setColumnData] = useState([]),
    [dataSource, setDataSource] = useState([]),
    [loading, setLoading] = useState(false);

  const initHandle = () => {
    setShowModal(true);
    fetchUnitSubmitInfosFunc();
  };

  const fetchUnitSubmitInfosFunc = async () => {
    setLoading(true);
    const res = await fetchUnitSubmitInfos(menuCode, currentSequenceId);
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      formatTableData(res.data?.programUnitList);
    } else {
      TRMessage.error(res?.message || messageConstant.FETCH_UNIT_SUBMIT_INFOS_ERROR_MESSAGE);
    }
  };

  const formatTableData = (tableData) => {
    let columnData = [],
      dataSource = Array.from({ length: 25 }, (_, index) => {
        // 所属方案名称
        if (index === 0) {
          let result = { hourOrder: '所属方案' };
          tableData.forEach(({ unitId, programTitle }) => {
            result[`${unitId}_content`] = programTitle || '-';
          });
          return result;
        } else {
          return { hourOrder: index };
        }
      });
    let { BUY, SELL, NOT_DEAL, NO_STRATEGY } = TRADE_STRATEGY;
    tableData.forEach(({ unitId, programTitle, unitProgramHourList, unitTitle }) => {
      columnData.push({ unitId, unitTitle });
      unitProgramHourList.forEach(
        ({ hourOrder, power, tradeStrategyType: strategy, lockedTradeType: lockedType }) => {
          let rowDs = dataSource[hourOrder];
          rowDs[`${unitId}_bk_class`] = getLockedBackgroundClassName(lockedType);
          if (programTitle) {
            switch (strategy) {
              case BUY:
                rowDs[`${unitId}_content`] = power.toFixed(3);
                rowDs[`${unitId}_font_class`] = `green`;
                rowDs[`${unitId}_conflict`] = lockedType === LOCKED_TYPE.SELL;
                break;
              case SELL:
                rowDs[`${unitId}_content`] = power.toFixed(3);
                rowDs[`${unitId}_font_class`] = `red`;
                rowDs[`${unitId}_conflict`] = lockedType === LOCKED_TYPE.BUY;
                break;
              case NOT_DEAL:
                rowDs[`${unitId}_content`] = `不交易`;
                rowDs[`${unitId}_font_class`] = `yellow`;
                break;
              case NO_STRATEGY:
                rowDs[`${unitId}_content`] = `无策略`;
                rowDs[`${unitId}_font_class`] = `gray`;
                break;
              default:
                break;
            }
          }
          // 没有所属方案
          else {
            rowDs[`${unitId}_content`] = '-';
            rowDs[`${unitId}_font_class`] = 'normal';
          }
        },
      );
    });

    setColumnData(columnData);
    setDataSource(dataSource);
  };

  const getLockedBackgroundClassName = (lockedType) => {
    let { BUY, SELL } = LOCKED_TYPE;
    switch (lockedType) {
      case BUY:
        return 'greenBackground';
      case SELL:
        return 'redBackground';
      default:
        return '';
    }
  };

  const modalTitleRender = () => (
    <div className={styles.modalTitle}>
      <div>
        <img src={programOverviewModal} />
        <span className={styles.text}>待申报方案总览</span>
        <Tooltip
          placement="bottom"
          title={
            <span>功能仅对当前未申报的方案进行汇总,以避免策略冲突或策略覆盖有遗漏的情况发生</span>
          }
        >
          <img className={styles.icon} src={question} />
        </Tooltip>
      </div>
      <div className={styles.unit}>
        <div>
          <span className={styles.label}>单位：</span>MWh
        </div>
        <div>
          <span className={styles.tradeForwordTitle}>窗口买卖方向限制</span>
          <span className={styles.sellIcon} />
          <span>卖出</span>
          <span className={styles.buyIcon} />
          <span>买入</span>
        </div>
      </div>
    </div>
  );
  const fetchTableRowClass = (record) => {
    if (record.hourOrder === '所属方案') {
      return 'extraInfo';
    }
  };
  const tableRowContentRender = (text, record, index, unitId) => {
    if (index == 0) {
      return <>{text}</>;
    }
    return (
      <span
        className={`${styles[record[`${unitId}_font_class`]]} ${
          styles[record[`${unitId}_bk_class`]]
        }`}
      >
        {record[`${unitId}_conflict`] ? <img className={styles.iconConflict} src={conflict} /> : ''}
        {text}
      </span>
    );
  };

  return (
    <Modal
      className={styles.programOverviewModal}
      centered={true}
      title={modalTitleRender()}
      visible={showModal}
      footer={null}
      onCancel={() => setShowModal(false)}
    >
      <Table
        loading={loading}
        className={styles.table}
        dataSource={dataSource}
        rowKey="hourOrder"
        locale={tableLocale}
        bordered={true}
        pagination={false}
        scroll={{ x: true }}
        rowClassName={fetchTableRowClass}
      >
        <Column
          title="时点"
          align="center"
          dataIndex="hourOrder"
          key="hourOrder"
          width={76}
          fixed="left"
        />
        {columnData.map(({ unitId, unitTitle }) => (
          <Column
            title={<div>{unitTitle}</div>}
            className={styles.stationsColumn}
            align="center"
            dataIndex={`${unitId}_content`}
            key={`${unitId}_content`}
            render={(text, record, index) => tableRowContentRender(text, record, index, unitId)}
          />
        ))}
      </Table>
    </Modal>
  );
}

export default connect(
  ({
    global: {
      configure: { menuCode },
    },
    rollingBatch: {
      globalSequence: {
        current: { tradeSequenceId: currentSequenceId },
      },
    },
  }) => ({ currentSequenceId, menuCode }),
  null,
  null,
  { forwardRef: true },
)(React.forwardRef(ProgramOverviewModal));
